﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;

namespace Lichtspiel.Audio
{
    public class Sound : IDisposable
    {
        // TODO looping, speed, volume
        private bool disposed = false;
        private SoundBuffer buffer;
        private int source;

        public SoundState State {
            get {
                int alState;
                AL.GetSource(source, ALGetSourcei.SourceState, out alState);

                ALSourceState state = (ALSourceState)alState;

                if (state == ALSourceState.Playing)
                    return SoundState.Playing;

                if (state == ALSourceState.Paused)
                    return SoundState.Paused;

                return SoundState.Stopped;
            }
        }

        public Sound(SoundBuffer buffer) {
            this.buffer = buffer;
            source = AL.GenSource();

            AL.Source(source, ALSourcei.Buffer, buffer.ID);
        }

        public void Play() {
            AL.SourcePlay(source);
        }

        public void Stop() {
            AL.SourceStop(source);
        }

        public void Pause() {
            AL.SourcePause(source);
        }        

        #region IDisposable Members

        public void Dispose() {
            Dispose(true);
        }

        private void Dispose(bool disposing) {
            // If you need thread safety, use a lock around these 
            // operations, as well as in your methods that use the resource.
            if (!disposed) {
                if (disposing) {

//                    buffer.Dispose(); 
                }
                AL.SourceStop(source);
                AL.DeleteSource(source);
                // Indicate that the instance has been disposed.
                disposed = true;
            }
        }

        #endregion
    }
}
